
package com.scalar.chiptrack.operations.dataentry.actions;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.StringTokenizer;
import java.sql.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.adaptor.TestLot;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.dataentry.dao.BinQuantity;
import com.scalar.chiptrack.operations.dataentry.dao.TestDataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.forms.TestDataEntryForm;
import com.scalar.chiptrack.operations.process.Lot;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.LotDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;

public final class TestDataEntryAction extends ChipTrackAction
{
	private static final String ACTION_NAME = "/testDataEntry.do" ;

	public TestDataEntryAction (){}

	public ActionForward execute ( ActionMapping mapping,
								   ActionForm form,
								   HttpServletRequest request,
								   HttpServletResponse response ) throws Exception
	{

		HttpSession session = request.getSession ();
		User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

		if ( user == null )
		{
			session.setAttribute (  SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME  );
			return ( mapping.findForward ( "login" ) );
		}
        else
        {
            if ( user.isActionAllowed ( Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

		ArrayList partNumberList 	= new ArrayList ();
		ArrayList binList 			= null;
		ArrayList testLocationList 	= null;
		ArrayList vendorLocationList 	= new ArrayList ();
		ArrayList partNumberSelectList 	= new ArrayList ();
		String action 				= request.getParameter ( "action" );
		String option 				= request.getParameter ( "option" );
		String confirm 				= request.getParameter ( "confirm" );
		String actionForward 		= "success";
		PartNumber partNumber 		= null;
		VendorLocation vendorLocation 	= null;
		HashMap errors 				= new LinkedHashMap ();
		HashMap info 				= new LinkedHashMap ();

		TestDataEntryForm testDataEntryForm = ( TestDataEntryForm ) form;
		TestDataEntryDAO testDataEntryDAO = new TestDataEntryDAO ();

		if ( action == null )
			action = "";
		if ( option == null )
		{
			option = "";
		}

		request.setAttribute ( "action", action );
		if ( confirm == null )
		confirm = "";

		partNumberList = ProductDao.getPartNumber( "TEST" );

		for ( int i = 0; i < partNumberList.size (); i++ )
		{
			partNumber = ( PartNumber ) partNumberList.get ( i );
			partNumberSelectList.add ( new org.apache.struts.util.LabelValueBean ( partNumber.getPartNumber (), partNumber.getProcessStepId () + "/" + partNumber.getPartNumber () ) );
		}

		request.setAttribute ( "partNumberSelectList", partNumberSelectList );

		if ( testLocationList == null )
			testLocationList = new ArrayList ( 0 );

		String locationId = testDataEntryForm.getLocationId ();
		String processStepId = testDataEntryForm.getProcessStepId ();
		String lotId = testDataEntryForm.getLotId ();

		if ( action.equals ( "location" ) || action.equals ( "save" ) || action.equals ( "lotnumber" ) || action.equals ( "partnumber" ) )
		{
			StringTokenizer st1 = new StringTokenizer ( processStepId, "/" );
			String pId = st1.nextToken ();
			st1.nextToken ();

			testLocationList = VendorDAO.getSelectedLocations ( Integer.parseInt ( pId ) );

			for ( int i = 0; i < testLocationList.size (); i++ )
			{
				vendorLocation = ( VendorLocation ) testLocationList.get ( i );
				vendorLocation.setLocationID ( vendorLocation.getLocationID () );
				vendorLocation.setLocationName ( vendorLocation.getLocationName () );
				vendorLocationList.add ( new org.apache.struts.util.LabelValueBean ( vendorLocation.getLocationName (), vendorLocation.getLocationID () + "/" + vendorLocation.getLocationName () ) );
			}
			request.removeAttribute ( "locationSelectList" );
			request.setAttribute ( "locationSelectList", vendorLocationList );
		}

		if ( action.equals ( "location" ) || action.equals ( "lotnumber" ) || action.equals ( "save" ) )
		{
			ArrayList list = getLotList ( processStepId, locationId );
			request.setAttribute ( "lotNumbers", list );
			if ( action.equals ( "location" ) )
			{
				testDataEntryForm.setLotId("0");
			}
		}

		if ( action.equals ( "lotnumber" ) )
		{
			StringTokenizer st1 = new StringTokenizer ( processStepId, "/" );
			String pId = st1.nextToken ();
			st1.nextToken ();

			if ( ( !"-1".equals ( lotId ) ) )
			{
				StringTokenizer st = new StringTokenizer ( lotId, "$" );
				String strLotId = st.nextToken ();
				st.nextToken ();
				st.nextToken ();

				TestDataEntryForm testLot = LotDAO.getTestLotData ( strLotId );

				testDataEntryForm.setQuantityIn ( testLot.getQuantityIn () );
				testDataEntryForm.setQuantityOut ( testLot.getQuantityOut () );
				testDataEntryForm.setPackageType ( testLot.getPackageType () );
				testDataEntryForm.setDateIn ( testLot.getDateIn () );
				testDataEntryForm.setDateOut ( testLot.getDateOut () );
				testDataEntryForm.setQuantityReject ( testLot.getQuantityReject () );
				testDataEntryForm.setYield ( testLot.getYield () );
				testDataEntryForm.setPoNumber( testLot.getPoNumber() );
				testDataEntryForm.setDateCode( testLot.getDateCode() );
				testDataEntryForm.setVendorLot( testLot.getVendorLot() );
				testDataEntryForm.setComments( testLot.getComments() );

				binList = testDataEntryDAO.getBinNumber ( Integer.parseInt ( pId ) );

				//Commented by ravikanth as for Running Lots we should not show Old Bin Information
				/*if ( binList != null )
				{
					testDataEntryDAO.getBinQuantities ( strLotId, binList );
				}*/

				request.setAttribute ( "binList", binList );
			}
			else
			{
				testDataEntryForm.setQuantityIn ( "" );
				testDataEntryForm.setQuantityOut ( "" );
				testDataEntryForm.setPackageType ( "" );
				testDataEntryForm.setDateIn ( StringUtils.formatDateToString(new Date(System.currentTimeMillis()), "MM/dd/yyyy") );
				testDataEntryForm.setDateOut ( "" );
				testDataEntryForm.setQuantityReject ( "" );
				testDataEntryForm.setYield ( "" );
				binList = testDataEntryDAO.getBinNumber ( Integer.parseInt ( pId ) );
				testDataEntryForm.setLotNo ( "" );
				request.setAttribute ( "binList", binList );
				testDataEntryForm.setPoNumber( "" );
				testDataEntryForm.setDateCode( "" );
				testDataEntryForm.setVendorLot( "" );
				testDataEntryForm.setComments( "" );
				testDataEntryForm.setPartialShippment(false);
			}
			request.setAttribute ( "lotnumber", "true" );
		}

        if( "allLotInfo".equals( action ) )
        {
            String lotprocessstepId = request.getParameter("ProcessStepId");
            String lotlocationId = request.getParameter("LocationId");
            String lotNo         = request.getParameter("LotNo");

            StringTokenizer st = new StringTokenizer ( lotprocessstepId, "/" );
            String pId = st.nextToken ();
            st.nextToken ();

            st = new StringTokenizer ( lotlocationId, "/" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList allLotsList = null;
            try
            {
                 String newlotId = LotDAO.getLotId( lotNo , locId, pId  );

                if ( newlotId != null && newlotId.length() > 0 )
                {
                    allLotsList = LotDAO.getAllLotDetails( newlotId );
                }

                request.setAttribute("allLotsList", allLotsList );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error while retreiving the Lot history list", null );
            }
            return mapping.findForward( "alllotInfo" );
        }

		if ( action.equals ( "save" ) )
		{
			String quantityIn 	= testDataEntryForm.getQuantityIn ();
			String quantityOut 	= testDataEntryForm.getQuantityOut ();
			String dateIn 		= testDataEntryForm.getDateIn ();
			String dateOut 		= testDataEntryForm.getDateOut ();
			String packageType 	= testDataEntryForm.getPackageType ();
			String qtyReject 	= testDataEntryForm.getQuantityReject ();
			String yield 		= testDataEntryForm.getYield ();
			String poNumber 	= testDataEntryForm.getPoNumber();
			String dateCode 	= testDataEntryForm.getDateCode();
			String vendorLot 	= testDataEntryForm.getVendorLot();
			String comments 	= testDataEntryForm.getComments();
			String lotCurrentStatus = "Running";

			if ( poNumber.equals ( "" ) || ( poNumber.trim().length() == 0 ) )
			{
				poNumber = null;
			}

			if ( quantityIn.equals ( "" ) )
			{
				quantityIn = null;
			}
			if ( dateIn.equals ( "" ) )
			{
				dateIn = null;
			}
			if ( quantityOut.trim ().equals ( "" ) )
			{
				quantityOut = null;
			}
			if ( dateOut.equals ( "" ) )
			{
				dateOut = null;
			}

			if( quantityOut != null )
			{
				lotCurrentStatus = "Close";
			}

			/*try
			{
				if( Integer.parseInt( quantityIn ) == Integer.parseInt( testDataEntryForm.getPartialShipQtyIn() ) )
				{
					lotCurrentStatus = "Close";
				}
			}
			catch( Exception e ){}*/

			try
			{
				StringTokenizer st1 = new StringTokenizer ( processStepId, "/" );
				String pId 			= st1.nextToken ();
				String pNumber 		= st1.nextToken ();
				String nextToken 	= st1.nextToken ();
				String testType 	= nextToken;
				testType 			= testType.trim ();

				binList = testDataEntryDAO.getBinNumber ( Integer.parseInt ( pId ) );
				String[] binQuantitys 	= testDataEntryForm.getBinQuantity ();
				LinkedHashMap binQtyMap = new LinkedHashMap ();
				BinQuantity binQty 		= null;
				ArrayList binQtyList 	= new ArrayList ();

				for ( int i = 0; i < binList.size (); i++ )
				{
					binQty = ( BinQuantity ) binList.get ( i );
					String binNumber = binQty.getBinNumber ();
					binQty.setBinQuantity ( binQuantitys[i] );
					binQtyMap.put ( binNumber, binQuantitys[i] );
					binQtyList.add ( binQty );
				}

				request.setAttribute ( "binList", binQtyList );

				String strLotId = null;
				String strLotNo = null;

				if ( !lotId.equals ( "-1" ) )
				{
					StringTokenizer st = new StringTokenizer ( testDataEntryForm.getLotId (), "$" );
					strLotId = st.nextToken ();
					strLotNo = st.nextToken ();
					st.nextToken ();
				}
				else
				{
					strLotId = "-1";
					strLotNo = testDataEntryForm.getLotNo ();
				}

				st1 = new StringTokenizer ( testDataEntryForm.getLocationId (), "/" );
				String locId = st1.nextToken ();
				String vendorName = st1.nextToken ();

				//check for duplication or lot number repetition.
				//***** This part of code does nothing but warns that this lot number already exists
				String lot_ID = LotDAO.getLotIdInDataEntry ( null, pId, locId, testDataEntryForm.getLotNo() );

				if( lot_ID == null )
				{
					lot_ID = "";
				}
				lot_ID = lot_ID.trim();

				if ( lotId.equals ( "-1" ) && ( !confirm.equals( "confirm" ) ) )
				{
					if ( "".equalsIgnoreCase( lot_ID ) == false )
					{
						request.setAttribute( "showError", "TRUE" );
						return mapping.findForward( "success" );
					}
				}
				// **********

				DBTransaction dbTransaction = null;
				boolean success = false;
				try
				{
					dbTransaction = DBTransaction.getInstance ();
					dbTransaction.begin ();
				}
				catch ( Exception e )
				{
					e.printStackTrace ();
				}

				ArrayList testLotList = new ArrayList ();

				TestLot testLot = new TestLot ();
				testLot.setPoNumber( poNumber );
				testLot.setDateCode( dateCode );
				testLot.setVendorLot( vendorLot );
				testLot.setComments( comments );
				/*testLot.setPartialshipQtyIn( testDataEntryForm.getPartialShipQtyIn() );
				testLot.setPartialshipQtyOut( testDataEntryForm.getPartialShipQtyOut() );
				testLot.setPartialShipDateOut( testDataEntryForm.getPartialShipDateOut() );*/

				testLotList.add ( testLot );

				LotDAO.changeLotStatusToCloseByLotId( dbTransaction, strLotId );

				LotDAO.saveTestLot ( dbTransaction, testLotList, user.getUserName (), testType );

				success = true;
				try
				{
					if ( success == true )
						dbTransaction.commit ();
					else
						dbTransaction.rollback ();
				}

				catch ( Exception e1 )
				{
					e1.printStackTrace ();
				}

				/*list = getLotList ( processStepId, locationId );

				if ( lotId.equals ( "-1" ) )
				{
					for ( int i = 0; i < list.size (); i++ )
					{
						LabelValueBean valueBean = ( LabelValueBean ) list.get ( i );
						String label = valueBean.getLabel ();
						if ( label.equals ( strLotNo ) )
						{
							testDataEntryForm.setLotId ( valueBean.getValue () );
						}
					}
				}*/

				actionForward = "saveSuccess";
			}
			catch( Exception e )
			{
				e.printStackTrace();
				errors.put( "Error storing the Test Lot information", null );
			}

			//request.setAttribute ( "lotNumbers", list );
			info.put ( "Data has been updated successfully", null );
		}
		request.removeAttribute ( "testdataentryform" );

		if ( action.equals("null") )
		{
			testDataEntryForm.setProcessStepId( "0" );
			request.setAttribute( SessionKeys.INFO_MESSAGES, request.getAttribute( SessionKeys.INFO_MESSAGES ) );
			request.setAttribute( SessionKeys.ERROR_MESSAGES, request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
		}
		else
		{
			request.setAttribute( SessionKeys.INFO_MESSAGES, info );
			request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		}
		request.setAttribute ( "testdataentryform", testDataEntryForm );

		return ( mapping.findForward ( actionForward ) );
	}

	private ArrayList getLotList ( String processStepId, String locationId )
	{
		java.util.ArrayList list = new ArrayList ();
		try
		{
			StringTokenizer st = new StringTokenizer ( processStepId, "/" );
			String pId = st.nextToken ();
			st.nextToken ();


			st = new StringTokenizer ( locationId, "/" );
			String locId = st.nextToken ();

			st.nextToken ();

			ArrayList lotNumberList = LotDAO.getRunningLotNumbersByPSTypeName ( pId, locId, "TEST" );
			Lot lot = null;
			list = new java.util.ArrayList ();

			for ( int i = 0; i < lotNumberList.size (); i++ )
			{
				lot = ( Lot ) lotNumberList.get ( i );
				list.add ( new org.apache.struts.util.LabelValueBean ( lot.getLotNumber (), lot.getLotId () + "$" + lot.getLotNumber () + "$" + lot.getStatus () ) );
			}
		}
		catch ( Exception e )
		{

		}
		return list;
	}
}